import { Injector, Input, OnChanges, OnInit, ViewChild } from '@angular/core';
import {
  Zone,
  ZoneService,
  ZoneResource,
  ZoneDetail,
  ChooseScope,
} from '../../../zone/services/zone.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { ListResult, ListOption, APIBase, ArrayAPIBase } from '../../../base/api-base';
import { MatDialogRef } from '@angular/material';
import { ActivatedRoute } from '@angular/router';
import { MySelection } from '../../../base/selection';
import { map, tap } from 'rxjs/operators';
import { ComputerService } from '../../services/computer.service';

export class ZoneResourceAddBase<T extends { id: number }> implements OnInit {
  constructor(
    private inject: Injector,
    private resource: ZoneResource,
    private route = inject.get(ActivatedRoute),
    protected computerService = inject.get(ComputerService),
    private dialog = inject.get(MatDialogRef),
  ) {}
  selection = new MySelection<T>('id');
  defaultOption = { scope: ChooseScope.selected };
  selectedService$ = this.selection.change.pipe(
    map(() => {
      const datasource = new ArrayAPIBase(this.selection.selected);
      datasource.search = (obj: any, keyword: string) => {
        keyword.toLowerCase();
        if (obj.name && obj.name.toLowerCase().includes(keyword)) {
          return true;
        }
        if (obj.full_name && obj.full_name.toLowerCase().includes(keyword)) {
          return true;
        }
        if (obj.job_number && obj.job_number.toLowerCase().includes(keyword)) {
          return true;
        }
        return false;
      };
      return datasource;
    }),
  );
  dataSource: APIBase<any, T>;
  zone: ZoneDetail;

  ngOnInit() {
    let r = this.route;
    while (r.firstChild) {
      r = r.firstChild;
    }
    const url=`/api/admin/pc/${r.snapshot.queryParams.id}/user`
    this.dataSource = this.computerService.allPerson(url);  
  }

  cancel() {
    this.dialog.close();
  }
  async save() {
    const zoo = this.route.snapshot.queryParams.id;
    const ids = this.selection.selected.map((obj) => obj.id);
    const url=`/api/admin/pc/${zoo}/user`;
    await this.computerService.createPerson(url,ids);
    this.dialog.close(true);
  }
}
